﻿using System;
using System.Data;
using System.IO;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;

/// <summary>
/// 使用Npoi操作Excel
/// </summary>
namespace NxERP.Bll
{
    public class NopiHelp
    {
        public NopiHelp()
        {
        }

        private static XSSFWorkbook BuildWorkbook(DataTable dt, string fileName, string sheetName, string cellTitle, bool isAutoID)
        {
            var book = new XSSFWorkbook();

            #region 设置单元格格式

            ICellStyle cellStyle = book.CreateCellStyle();
            cellStyle.VerticalAlignment = VerticalAlignment.Center;//垂直对齐
            cellStyle.Alignment = HorizontalAlignment.Center;//水平对齐
            cellStyle.BorderBottom = BorderStyle.Thin;
            cellStyle.BorderLeft = BorderStyle.Thin;
            cellStyle.BorderRight = BorderStyle.Thin;
            cellStyle.BorderTop = BorderStyle.Thin;

            #endregion 设置单元格格式

            if (sheetName == "" || sheetName == null)
            {
                sheetName = "Sheet1";
            }
            int headRowIndex = 0;
            ISheet sheet = book.CreateSheet(sheetName);
            if (cellTitle != "" && cellTitle != null)
            {
                ICellStyle titleCellStyle = book.CreateCellStyle();
                titleCellStyle.VerticalAlignment = VerticalAlignment.Center;
                titleCellStyle.Alignment = HorizontalAlignment.Center;
                IFont font = book.CreateFont();
                font.FontHeightInPoints = 16;
                font.IsBold = true;
                //Title Rows
                IRow titleRow = sheet.CreateRow(0);
                if (isAutoID == true)
                {
                    sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns.Count));
                }
                else
                {
                    sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns.Count - 1));
                }
                ICell titleCell = titleRow.CreateCell(0, CellType.String);
                titleCell.SetCellValue(cellTitle);
                titleCellStyle.SetFont(font);
                titleCell.CellStyle = titleCellStyle;
                headRowIndex = 1;
            }
            //Head Rows
            IRow headRow = sheet.CreateRow(headRowIndex);
            for (int k = 0; k < dt.Columns.Count; k++)
            {
                if (isAutoID == true)
                {
                    ICell idCell = headRow.CreateCell(0, CellType.String);
                    idCell.SetCellValue("序号");
                    idCell.CellStyle = cellStyle;
                    ICell headCell = headRow.CreateCell(k + 1, CellType.String);
                    headCell.SetCellValue(dt.Columns[k].Caption);
                    headCell.CellStyle = cellStyle;
                }
                else
                {
                    ICell headCell = headRow.CreateCell(k, CellType.String);
                    headCell.SetCellValue(dt.Columns[k].Caption);
                    headCell.CellStyle = cellStyle;
                }
            }
            //Data Rows
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow drow = sheet.CreateRow(i + 1 + headRowIndex);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (isAutoID == true)
                    {
                        ICell idCell = drow.CreateCell(0, CellType.Numeric);
                        idCell.SetCellValue(i + 1);
                        idCell.CellStyle = cellStyle;
                        ICell cell = drow.CreateCell(j + 1, CellType.String);
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                        cell.CellStyle = cellStyle;
                    }
                    else
                    {
                        ICell cell = drow.CreateCell(j, CellType.String);
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                        cell.CellStyle = cellStyle;
                    }
                }
            }
            //自动列宽
            for (int i = 0; i <= dt.Columns.Count; i++)
                sheet.AutoSizeColumn(i, true);

            return book;
        }

        /// <summary>
        /// 导出Execl，net4.5以上调用这个，对应nopi2.4以上
        /// </summary>
        /// <param name="dt">       要导出的DataTable</param>
        /// <param name="fileName"> 导出的文件名</param>
        /// <param name="sheetName">工作薄名称，为空使用默认Sheet1</param>
        /// <param name="titleCell">标题名称，为空无标题</param>
        /// <param name="isAutoID"> true时第一列生产一列序号</param>
        /// <param name="xlsVison"> 要导出的excel版本，xls或者xlsx</param>
        public static void ExportExcel(DataTable dt, string fileName, string sheetName, string titleCell, bool isAutoID, string xlsVison)
        {
            if (xlsVison == "" || xlsVison == null)
            {
                xlsVison = "xlsx";
            }
            xlsVison = "." + xlsVison;
            //生成Excel
            IWorkbook book = BuildWorkbook(dt, fileName, sheetName, titleCell, isAutoID);
            //WEB 下载
            if (fileName == "")
                fileName = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now);
            fileName = fileName.Trim();
            string ext = Path.GetExtension(fileName);
            if (ext.ToLower() != ".xls" && ext.ToLower() == ".xlsx")
            {
                fileName = fileName.Replace(ext, string.Empty);
                fileName += xlsVison;
            }
            using (var fs = File.OpenWrite(fileName))
            {
                book.Write(fs);
            }
        }

        /// <summary>
        /// net4.0调用这个，对应nopi2.3
        /// </summary>
        /// <param name="dt">       </param>
        /// <param name="fileName"> </param>
        /// <param name="sheetName"></param>
        public static void ExportExcel(DataTable dt, string fileName, string sheetName)
        {
            IWorkbook workbook = new HSSFWorkbook();

            #region 设置单元格格式

            ICellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.VerticalAlignment = VerticalAlignment.Center;//垂直对齐
            cellStyle.Alignment = HorizontalAlignment.Center;//水平对齐
            cellStyle.BorderBottom = BorderStyle.Thin;
            cellStyle.BorderLeft = BorderStyle.Thin;
            cellStyle.BorderRight = BorderStyle.Thin;
            cellStyle.BorderTop = BorderStyle.Thin;

            #endregion 设置单元格格式

            string fileExt = Path.GetExtension(fileName).ToLower();
            if (fileExt != ".xlsx" && fileExt != ".xls")
            {
                workbook = null;
            }
            if (workbook == null) { return; }
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet(sheetName) : workbook.CreateSheet(dt.TableName);

            //表头
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell idCell = row.CreateCell(0, CellType.Numeric);
                idCell.SetCellValue("序号");
                idCell.CellStyle = cellStyle;
                ICell cell = row.CreateCell(i + 1);
                cell.SetCellValue(dt.Columns[i].ColumnName);
                cell.CellStyle = cellStyle;
            }

            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell idCell = row1.CreateCell(0, CellType.Numeric);
                    idCell.SetCellValue(i + 1);
                    idCell.CellStyle = cellStyle;
                    ICell cell = row1.CreateCell(j + 1);
                    if (double.TryParse(dt.Rows[i][j].ToString(), out double value3))
                    {
                        cell.SetCellValue(value3);
                    }
                    else
                    {
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                    }
                    cell.CellStyle = cellStyle;
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 将excel导入到datatable
        /// </summary>
        /// <param name="filePath">    Excel路径</param>
        /// <param name="isColumnName">第一行是否是列名</param>
        /// <returns>返回DataTable</returns>
        public static DataTable ExcelToDataTable(string filePath, string sheetName, bool isColumnName)
        {
            DataTable dataTable = null;
            FileStream fs = null;
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            try
            {
                using (fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    // 2007版本
                    if (filePath.IndexOf(".xlsx") > 0)
                        workbook = new XSSFWorkbook(fs);
                    // 2003版本
                    else if (filePath.IndexOf(".xls") > 0)
                        workbook = new HSSFWorkbook(fs);

                    if (workbook != null)
                    {
                        sheet = workbook.GetSheet(sheetName);//读取第一个sheet，当然也可以循环读取每个sheet
                        dataTable = new DataTable();
                        if (sheet != null)
                        {
                            int rowCount = sheet.LastRowNum;//总行数
                            if (rowCount > 0)
                            {
                                IRow firstRow = sheet.GetRow(0);//第一行
                                int cellCount = firstRow.LastCellNum;//列数

                                //构建datatable的列
                                if (isColumnName)
                                {
                                    startRow = 1;//如果第一行是列名，则从第二行开始读取
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        cell = firstRow.GetCell(i);
                                        if (cell != null)
                                        {
                                            if (cell.StringCellValue != null)
                                            {
                                                column = new DataColumn(cell.StringCellValue);
                                                dataTable.Columns.Add(column);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        column = new DataColumn("column" + (i + 1));
                                        dataTable.Columns.Add(column);
                                    }
                                }

                                //填充行
                                for (int i = startRow; i <= rowCount; ++i)
                                {
                                    row = sheet.GetRow(i);
                                    if (row == null) continue;

                                    dataRow = dataTable.NewRow();
                                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                                    {
                                        cell = row.GetCell(j);
                                        if (cell == null)
                                        {
                                            dataRow[j] = "";
                                        }
                                        else
                                        {
                                            //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                            switch (cell.CellType)
                                            {
                                                case CellType.Blank:
                                                    dataRow[j] = "";
                                                    break;

                                                case CellType.Numeric:
                                                    short format = cell.CellStyle.DataFormat;
                                                    //对时间格式（2015.12.5、2015/12/5、2015-12-5等）的处理
                                                    if (format == 14 || format == 31 || format == 57 || format == 58)
                                                        dataRow[j] = cell.DateCellValue;
                                                    else
                                                        dataRow[j] = cell.NumericCellValue;
                                                    break;

                                                case CellType.String:
                                                    dataRow[j] = cell.StringCellValue;
                                                    break;
                                            }
                                        }
                                    }
                                    dataTable.Rows.Add(dataRow);
                                }
                            }
                        }
                    }
                }
                return dataTable;
            }
            catch
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return null;
            }
        }

        public static DataTable ExcelToDataTable(string filePath, bool isColumnName, string sheetName)
        {
            DataTable dataTable = null;
            FileStream fs = null;
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            try
            {
                using (fs = File.OpenRead(filePath))
                {
                    // 2007版本
                    if (filePath.IndexOf(".xlsx") > 0)
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    // 2003版本
                    else if (filePath.IndexOf(".xls") > 0)
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    if (workbook != null)
                    {
                        sheet = workbook.GetSheet(sheetName);//读取指定sheet
                        dataTable = new DataTable();
                        if (sheet != null)
                        {
                            int rowCount = sheet.LastRowNum;//总行数
                            if (rowCount > 0)
                            {
                                IRow firstRow = sheet.GetRow(0);//第一行
                                int cellCount = firstRow.LastCellNum;//列数

                                //构建datatable的列
                                if (isColumnName)
                                {
                                    startRow = 1;//如果第一行是列名，则从第二行开始读取
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        cell = firstRow.GetCell(i);
                                        if (cell != null)
                                        {
                                            if (cell.StringCellValue != null)
                                            {
                                                column = new DataColumn(cell.StringCellValue);
                                                dataTable.Columns.Add(column);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        column = new DataColumn("F" + (i + 1));
                                        dataTable.Columns.Add(column);
                                    }
                                }

                                //填充行
                                for (int i = startRow; i <= rowCount; ++i)
                                {
                                    row = sheet.GetRow(i);
                                    if (row == null) continue;

                                    dataRow = dataTable.NewRow();
                                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                                    {
                                        cell = row.GetCell(j);
                                        if (cell == null)
                                        {
                                            dataRow[j] = "";
                                        }
                                        else
                                        {
                                            //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                            switch (cell.CellType)
                                            {
                                                case CellType.Blank:
                                                    dataRow[j] = "";
                                                    break;

                                                case CellType.Numeric:
                                                    short format = cell.CellStyle.DataFormat;
                                                    //对时间格式（2015.12.5、2015/12/5、2015-12-5等）的处理
                                                    if (DateUtil.IsCellDateFormatted(cell))
                                                        dataRow[j] = cell.DateCellValue;
                                                    else
                                                        dataRow[j] = cell.NumericCellValue;
                                                    break;

                                                case CellType.String:
                                                    dataRow[j] = cell.StringCellValue;
                                                    break;
                                            }
                                        }
                                    }
                                    dataTable.Rows.Add(dataRow);
                                }
                            }
                        }
                    }
                }
                return dataTable;
            }
            catch (Exception)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return null;
            }
        }

        public static bool CheckSheetName(string filePath, string sheetName)
        {
            FileStream fs = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            bool rt = false;
            try
            {
                using (fs = File.OpenRead(filePath))
                {
                    // 2007版本
                    if (filePath.IndexOf(".xlsx") > 0)
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    // 2003版本
                    else if (filePath.IndexOf(".xls") > 0)
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    if (workbook != null)
                    {
                        sheet = workbook.GetSheet(sheetName);//读取指定sheet
                        if (sheet != null)
                        {
                            rt = true;
                        }
                    }
                }
            }
            catch { }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
            return rt;
        }
    }
}